package com.wildlife.springboot.mapper.service;

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Service
public class ImagesUploadService {

    private static final String UPLOAD_DIR = "images/";

    public List<String> uploadImages(List<MultipartFile> files) throws IOException {
        // 确保上传目录存在
        Path uploadPath = Paths.get(UPLOAD_DIR);
        if (!Files.exists(uploadPath)) {
            Files.createDirectories(uploadPath);
        }

        List<String> uploadedFilePaths = new ArrayList<>();

        for (MultipartFile file : files) {
            // 获取文件名并生成唯一文件名
            String originalFilename = file.getOriginalFilename();
            String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String uniqueFilename = UUID.randomUUID().toString() + fileExtension;

            // 保存文件到上传目录
            Path filePath = uploadPath.resolve(uniqueFilename);
            Files.copy(file.getInputStream(), filePath);

            // 将文件路径添加到列表中
            uploadedFilePaths.add(filePath.toString());
        }
        return uploadedFilePaths;
    }
}
